package com.mybatis.sqlsession;

import com.mybatis.entity.Configuration;
import com.mybatis.entity.MappedStatement;
import com.mybatis.utils.ClassUtil;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建人: yyn
 * 创建时间:2021/7/9 22:23
 */
public class SimpleResultSetHandler implements ResultSetHandler {
    private Configuration configuration;

    public SimpleResultSetHandler(Configuration configuration) {
        this.configuration = configuration;
    }

    public <T> List<T> handleResult(PreparedStatement preparedStatement, MappedStatement mappedStatement) throws Exception {
        ResultSet resultSet = preparedStatement.executeQuery();
        List<T> result = new ArrayList<>();
        Class<?> resultClassType = ClassUtil.getClassType(mappedStatement.getResultType());
        while (resultSet.next()) {
            Object o = resultClassType.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClassType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            result.add((T) o);
        }
        return result;
    }
}
